package _18_剑指OfferII;

import _18_剑指OfferII.datastrcute.TreeNode;

import java.util.Arrays;
import java.util.LinkedList;

public class _048_剑指OfferII序列化与反序列化二叉树 {

    // 存放空节点
    private static final String EMPTY = "#";

    // 存放分隔符，因为一位数字和多位数字很难区分
    private static final String SPLIT = "!";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root, sb);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        return deserialize(new LinkedList<>(Arrays.asList(data.split(SPLIT))));
    }

    // 反序列化和序列化逻辑一样使用前序遍历
    private TreeNode deserialize(LinkedList<String> list) {
        String value = list.poll();
        if (EMPTY.equals(value)) return null;
        TreeNode root = new TreeNode(Integer.parseInt(value));
        root.left = deserialize(list);
        root.right = deserialize(list);
        return root;
    }

    private void serialize(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append(EMPTY).append(SPLIT);
            return;
        }
        sb.append(root.val).append(SPLIT);
        serialize(root.left, sb);
        serialize(root.right, sb);
    }

}
